package com.cl.mypureframe.conn;

import android.content.Context;

import com.cl.mypureframe.BaseApplication;
import com.cl.mypureframe.R;
import com.cl.mypureframe.dialog.MProgressDialog;
import com.cl.mypureframe.minterface.OnResponseCallback;
import com.cl.mypureframe.minterface.OnResponseSuccessCallback;
import com.cl.mypureframe.util.Log;
import com.cl.mypureframe.util.UtilToast;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 网络工具类
 * <p>
 * Created by Lei
 * on 2020/10/15
 */
public class RetrofitUtil<T> {
    private final String TAG = Log.getTag(RetrofitUtil.class);

    public ConnApiInterface getRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Conn.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(getHttpClinet())
                .build();
        return retrofit.create(ConnApiInterface.class);
    }

    public OkHttpClient getHttpClinet() {
        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Cookie", "0");
                    Request request = requestBuilder.build();

                    okhttp3.Response response = chain.proceed(request);
                    Log.i(TAG, "请求链接：", request.url());
                    Log.d(TAG, "请求头：", getRequestHeaders(request));
                    Log.i(TAG, "请求参数：", getRequestInfo(request));
                    Log.w(TAG, "请求响应：", getResponseInfo(response));
                    Log.v(TAG, "响应头：", getResponseHeaders(response));

                    return response;
                }).build();
    }

    /**
     * 打印请求头
     *
     * @param request 请求的对象
     */
    private String getRequestHeaders(Request request) {
        String str = "";
        if (request == null) {
            return str;
        }
        Headers headers = request.headers();
        return headers.toString();
    }

    private String getResponseHeaders(okhttp3.Response respons) {
        String str = "";
        if (respons == null) {
            return str;
        }
        Headers headers = respons.headers();
        return headers.toString();
    }

    /**
     * 打印请求消息
     *
     * @param request 请求的对象
     */
    private String getRequestInfo(Request request) {
        String str = "";
        if (request == null) {
            return str;
        }
        RequestBody requestBody = request.body();
        if (requestBody == null) {
            return str;
        }
        try {
            Buffer bufferedSink = new Buffer();
            requestBody.writeTo(bufferedSink);
            Charset charset = StandardCharsets.UTF_8;
            str = bufferedSink.readString(charset);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 打印返回消息
     *
     * @param response 返回的对象
     */
    private String getResponseInfo(okhttp3.Response response) {
        String str = "";
        if (response == null || !response.isSuccessful()) {
            if (response != null) {
                str = response.toString();
            }
            return str;
        }
        ResponseBody responseBody = response.body();
        long contentLength;
        if (responseBody != null) {
            contentLength = responseBody.contentLength();
            BufferedSource source = responseBody.source();
            try {
                source.request(Long.MAX_VALUE); // Buffer the entire body.
            } catch (IOException e) {
                e.printStackTrace();
            }
            Buffer buffer = source.getBuffer();
            Charset charset = StandardCharsets.UTF_8;
            if (contentLength != 0) {
                str = buffer.clone().readString(charset);
            }
        }
        return str;
    }

    public void connAction(Call<T> call, Context context, OnResponseSuccessCallback<T> onResponseSuccessCallback) {
        connActionBase(call, context, null, onResponseSuccessCallback, true);
    }

    // 没有加载对话框的
    public void connActionNoProgressDialog(Call<T> call, Context context, OnResponseSuccessCallback<T> onResponseSuccessCallback) {
        connActionBase(call, context, null, onResponseSuccessCallback, false);
    }

    public void connAction(Call<T> call, Context context, final OnResponseCallback<T> onResponseCallback) {
        connActionBase(call, context, onResponseCallback, null, true);

    }

    // 没有加载对话框的
    public void connActionNoProgressDialog(Call<T> call, Context context, final OnResponseCallback<T> onResponseCallback) {
        connActionBase(call, context, onResponseCallback, null, false);
    }

    public void connActionBase(Call<T> call, Context context, final OnResponseCallback<T> onResponseCallback,
                               final OnResponseSuccessCallback<T> onResponseSuccessCallback, boolean isShowProgressDialog) {
        final MProgressDialog progressDialog = new MProgressDialog(context);
        if (isShowProgressDialog) {
            progressDialog.show();
        }
        if (onResponseCallback != null) {
            onResponseCallback.onStartCallback();
        }
        // noinspection NullableProblems
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                T t = response.body();
                if (t != null) {
                    // 返回成功
                    if (onResponseCallback != null) {
                        onResponseCallback.onSuccessCallback(response);
                    }
                    if (onResponseSuccessCallback != null) {
                        onResponseSuccessCallback.onSuccessCallback(response);
                    }

                } else {
                    if (isShowProgressDialog) {
                        UtilToast.show(R.string.to_data_error);
                    }
                    if (onResponseCallback != null) {
                        onResponseCallback.onErrorCallback();
                    }
                }
                if (onResponseCallback != null) {
                    onResponseCallback.onEndCallback();
                }
                if (isShowProgressDialog) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                if (onResponseCallback != null) {
                    onResponseCallback.onErrorCallback();
                    onResponseCallback.onEndCallback();
                }
                Log.e(TAG, "onFailure:" + t.getMessage());
                if (isShowProgressDialog) {
                    UtilToast.show(R.string.to_net_error);
                    progressDialog.dismiss();
                }
            }
        });

    }

}
